package com.dw.dwdzcommerce.tools.uiView.smartMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dw.dwdzcommerce.R;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.graphics.drawable.DrawerArrowDrawable.ArrowDirection;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 二级联动三选项菜单
 * 
 * @author 周稹
 *
 */
public class SmartMenu extends LinearLayout implements OnClickListener {
	private WindowManager manager;
	private int screenWidth, menuheight = 35;
	private TextLayout mLvFirstBtn, mLvSecBtn, mLvThirdBtn;
	private List<String> optionOne, optionTwo, optionThree;
	private Map<String, List<String>> smartSecondRelevancy;// 第一、二级关联
	private Map<String, Map<String, List<String>>> smartThirdRelevancy; // 一二三级关联
	private boolean isSecondRelevancy = false;
	private boolean isThirdRelevancy = false;
	private boolean isLimitTwo = false;
	private String firstText, secText;
	private Context context;
	private ListView mListViewOptionOne, mListViewOptionTwo, mListViewOptionThree;
	public static final int OPTION_ONE = 1;
	public static final int OPTION_TWO = 2;
	public static final int OPTION_THIRD = 3;
	private int currOption = OPTION_ONE;
	private OnMenuClickListener listener;
	private PopupWindow ppw;
	private int itemHightDp = 0;
	private OnMenuExpendListener expendlistener;
	private OnMenuCloseListener closelistener;
	private int styleRes;
	private float btnTextSize;

	private int expendRes = getResources().getColor(R.color.btn_text_color_pressed);
	private int closeRes = getResources().getColor(R.color.btn_text_color_unpressed);

	/**
	 * 设置一二级关联
	 */
	public void setRelevancy(String parent, List<String> child) {
		if (parent != null && child != null) {
			optionOne.add(parent);
			smartSecondRelevancy.put(parent, child);
		} else {
			throw new RuntimeException("两级关联非法参数");
		}
	}

	/**
	 * 设置一二三级关联子集
	 */
	public void setRelevancy(Map<String, Map<String, List<String>>> child) {
		this.smartThirdRelevancy = child;
		getOptionOne(child);

	}

	/**
	 * 设置是否取消第三个菜单
	 * 
	 * @param isLimitTwo
	 */
	public void setIsLimitTwo(boolean isLimitTwo) {
		this.isLimitTwo = isLimitTwo;
		this.isThirdRelevancy = false;
	}

	/**
	 * 设置是否一二级关联
	 * 
	 * @param isSecondRelevance
	 */
	public void setSecondRelevancy(boolean isSecondRelevance) {
		this.isSecondRelevancy = isSecondRelevance;
		if (isSecondRelevance) {
			isThirdRelevancy = false;
		}
	}

	/**
	 * 设置是否三级关联
	 * 
	 * @param isThirdRelevancy
	 */
	public void setThirdRelevancy(boolean isThirdRelevancy) {
		this.isThirdRelevancy = isThirdRelevancy;
		if (isThirdRelevancy) {
			isSecondRelevancy = false;
		}
	}

	public void setIsRelevancy(boolean isRelevancy) {
		if (!isRelevancy) {
			isThirdRelevancy = false;
			isSecondRelevancy = false;
		}
	}

	/**
	 * 设置第一级菜单
	 * 
	 * @param optionOne
	 */
	public void setFirstOption(List<String> optionOne) {
		this.optionOne = optionOne;
	}

	/**
	 * 设置二级菜单
	 * 
	 * @param optionTwo
	 */
	public void setSecondOption(List<String> optionTwo) {
		this.optionTwo = optionTwo;
	}

	/**
	 * 设置三级菜单
	 */
	public void setThirdOption(List<String> optionThree) {
		this.optionThree = optionThree;
	}

	public SmartMenu(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public SmartMenu(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SmartMenu(Context context) {
		this(context, null);
	}

	/**
	 * 设置按钮子号
	 * 
	 * @param sp
	 *            sp
	 */
	public void setBtnTextSize(int sp) {
		this.btnTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
				getResources().getDisplayMetrics());
	}

	/**
	 * 获得对应的按钮
	 * 
	 * @param option
	 * @return
	 */
	public TextLayout getButton(int option) {
		switch (option) {
		case OPTION_ONE:
			return mLvFirstBtn;
		case OPTION_TWO:
			return mLvSecBtn;
		case OPTION_THIRD:
			return mLvThirdBtn;
		}
		return null;
	}

	/**
	 * 根据设置创建并显示控件
	 */
	public void show() {
		// 初始化子控件
		if (isSecondRelevancy) {
			initRelevencyChlidLayout(context);
		} else if (isThirdRelevancy) {
			initThirdRelevancyChildLayout(context);
		} else {
			initUnRelevancyChildLayout(context);
		}
		// 初始化父布局
		initParentLayout();
		// 初始化菜单列表
		initMenuListView();
		List<String> itemCurrentState = getItemCurrentState();

		listener.onMenuClick(itemCurrentState.get(0), itemCurrentState.get(1), null);

	}

	private void initMenuListView() {
		mListViewOptionOne = getListView(optionOne);
		mListViewOptionTwo = getSecondListView();
		mListViewOptionThree = getThirdListView();
		setOnItemClickListener();
	}

	private ListView getThirdListView() {
		if (isThirdRelevancy) {
			// Map<String, Map<String, List<String>>>
			return getListView(getOptionThreeFromTwo(optionTwo.get(0)));
		} else {
			return getListView(optionThree);
		}
	}

	private ListView getSecondListView() {

		if (isSecondRelevancy) {
			return getListView(smartSecondRelevancy.get(optionOne.get(0)));
		} else if (isThirdRelevancy) {
			return getListView(getOptionTwoFromOne(optionOne.get(0)));
		} else {	
			return getListView(optionTwo);
		}
	}

	// 从三级关联中取一级集合
	private List<String> getOptionOne(Map<String, Map<String, List<String>>> child) {
		optionOne = new ArrayList<String>(child.keySet());
		return optionOne;
	}

	// 从三级关联中获取二级的集合
	private List<String> getOptionTwoFromOne(String firstText) {
		this.firstText = firstText;
		optionTwo = new ArrayList<String>(smartThirdRelevancy.get(firstText).keySet());
		return optionTwo;
	}

	// 从三级关联中获取三级的集合
	private List<String> getOptionThreeFromTwo(String secText) {
		this.secText = secText;
		optionThree = smartThirdRelevancy.get(firstText).get(secText);
		return optionThree;
	}

	// 设置菜单列表的点击事件
	private void setOnItemClickListener() {
		mListViewOptionOne.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 获得当前单击的条目值
				String text = getTextFromView(view);
				mLvFirstBtn.setText(text);
				if (isSecondRelevancy) {
					setSecondBtnRelevancy(text);
				} else if (isThirdRelevancy) {
					setThirdRelevancy(text);
				}
				mListViewOptionTwo.setOnItemClickListener(getOnclickListener(OPTION_TWO));
				mListViewOptionThree.setOnItemClickListener(getOnclickListener(OPTION_THIRD));
				disMissPpw();
				if (!isLimitTwo) {
					callback(mLvFirstBtn.getText().toString(), mLvSecBtn.getText().toString(),
							mLvThirdBtn.getText().toString());
				} else {
					callback(mLvFirstBtn.getText().toString(), mLvSecBtn.getText().toString(), "");
				}

			}

			private void setThirdRelevancy(String text) {
				optionTwo = getOptionTwoFromOne(text);
				if (optionTwo.size() != 0) {
					mLvSecBtn.setText(optionTwo.get(0));
					mLvThirdBtn.setText(getOptionThreeFromTwo(optionTwo.get(0)).get(0));
				} else {
					mLvSecBtn.setText("无");
					mLvThirdBtn.setText("无");
				}

			}

			private void setSecondBtnRelevancy(String text) {
				// 通过关联map得到该条目支所对应的集合
				List<String> menuTwo = smartSecondRelevancy.get(text);
				// 给第一、第二个按钮初始化值
				if (menuTwo.size() != 0) {
					mLvSecBtn.setText(menuTwo.get(0));
				} else {
					mLvSecBtn.setText("");
				}

				// 将菜单列表更新
				mListViewOptionTwo = getListView(menuTwo);
			}
		});
		mListViewOptionTwo.setOnItemClickListener(getOnclickListener(OPTION_TWO));
		mListViewOptionThree.setOnItemClickListener(getOnclickListener(OPTION_THIRD));
	}

	public void setShowAnimStyle(int styleRes) {
		this.styleRes = styleRes;
	}

	private OnItemClickListener getOnclickListener(final int option) {
		return new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String textFromView = getTextFromView(view);
				if (option == OPTION_TWO) {
					mLvSecBtn.setText(textFromView);
				} else {
					mLvThirdBtn.setText(textFromView);
				}
				disMissPpw();
				if (!isLimitTwo) {
					callback(mLvFirstBtn.getText().toString(), mLvSecBtn.getText().toString(),
							mLvThirdBtn.getText().toString());
				} else {
					callback(mLvFirstBtn.getText().toString(), mLvSecBtn.getText().toString(), "");
				}
			}

		};
	}

	private void callback(String menu1, String menu2, String menu3) {
		if (listener != null) {
			listener.onMenuClick(menu1, menu2, menu3);
		}
	}

	private String getTextFromView(View view) {
		TextView mTextView = (TextView) view.findViewById(R.id.tv_smartmenu);
		String text = mTextView.getText().toString();
		return text;
	}

	private void init(Context context) {
		this.context = context;
		// 给参数赋值
		initWindowParams(context);
		// 初始化容器
		initContainer();

		setBackgroundColor(getResources().getColor(R.color.gray));
	}

	// 添加一二关联性子类
	private void initRelevencyChlidLayout(Context context) {
		mLvFirstBtn = getDisplayButton(context);
		mLvFirstBtn.setTag(OPTION_ONE);
		mLvSecBtn = getDisplayButton(context);
		mLvSecBtn.setTag(OPTION_TWO);
		if (!isLimitTwo) {
			mLvThirdBtn = getDisplayButton(context);
			mLvThirdBtn.setTag(OPTION_THIRD);
			if (optionThree != null && optionThree.size() != 0) {
				mLvThirdBtn.setText(optionThree.get(0));
			}
		}
		// if (isSecReady && isThirdReady)
		// {
		String optOne = optionOne.get(0);
		mLvFirstBtn.setText(optOne);
		mLvSecBtn.setText(smartSecondRelevancy.get(optOne).get(0));

		// }
		setChlidOnclickListener();
	}

	// 添加一二三级关联子类
	private void initThirdRelevancyChildLayout(Context context) {
		mLvFirstBtn = getDisplayButton(context);
		mLvFirstBtn.setTag(OPTION_ONE);
		mLvSecBtn = getDisplayButton(context);
		mLvSecBtn.setTag(OPTION_TWO);
		mLvThirdBtn = getDisplayButton(context);
		mLvThirdBtn.setTag(OPTION_THIRD);
		// if (isSecReady && isThirdReady)
		// {
		optionTwo = getOptionTwoFromOne(optionOne.get(0));
		optionThree = getOptionThreeFromTwo(optionTwo.get(0));
		mLvFirstBtn.setText(optionOne.get(0));
		mLvSecBtn.setText(optionTwo.get(0));
		mLvThirdBtn.setText(optionThree.get(0));
		// }
		setChlidOnclickListener();

	}

	// 添加三级非关联性子类
	private void initUnRelevancyChildLayout(Context context) {

		mLvFirstBtn = getDisplayButton(context);
		mLvFirstBtn.setTag(OPTION_ONE);
		mLvSecBtn = getDisplayButton(context);
		mLvSecBtn.setTag(OPTION_TWO);
		if (!isLimitTwo) {
			mLvThirdBtn = getDisplayButton(context);
			mLvThirdBtn.setTag(OPTION_THIRD);
			mLvThirdBtn.setText(optionThree.get(0));
		}
		// if (isSecReady && isThirdReady)
		// {
		mLvFirstBtn.setText(optionOne.get(0));
		mLvSecBtn.setText(optionTwo.get(0));
		// }
		setChlidOnclickListener();

	}

	private void setChlidOnclickListener() {
		mLvFirstBtn.setOnClickListener(this);
		mLvSecBtn.setOnClickListener(this);
		if (!isLimitTwo) {
			mLvThirdBtn.setOnClickListener(this);
		}
	}

	private void initParentLayout() {
		this.setOrientation(LinearLayout.HORIZONTAL);
		// 这里取到的是当前控件的上级布局的LayoutParams
		LayoutParams layoutParams = (LayoutParams) this.getLayoutParams();
		layoutParams.width = screenWidth;
		layoutParams.gravity = Gravity.CENTER;
		this.setLayoutParams(layoutParams);
		this.addView(mLvFirstBtn);
		this.addView(mLvSecBtn);
		if (!isLimitTwo) {
			this.addView(mLvThirdBtn);
		}
	}

	private void initContainer() {
		optionOne = new ArrayList<String>();
		optionTwo = new ArrayList<String>();
		optionThree = new ArrayList<String>();
		smartSecondRelevancy = new HashMap<String, List<String>>();
	}

	// 得到按钮对象
	// TODO
	private TextLayout getDisplayButton(Context context) {
		TextLayout mButton = new TextLayout(context);
		mButton.init();
		if (!isLimitTwo) {
			mButton.setLayoutParams(new LayoutParams(screenWidth / 3, LayoutParams.MATCH_PARENT));
		} else {
			mButton.setLayoutParams(new LayoutParams(screenWidth / 2, LayoutParams.MATCH_PARENT));
		}
		LinearLayout.LayoutParams params = (LayoutParams) mButton.getLayoutParams();
		params.leftMargin = 3;
		params.rightMargin = 3;
		mButton.setTextColor(closeRes);
		mButton.setLayoutParams(params);
		mButton.setPadding(0, 5, 0, 5);
		return mButton;
	}

	// 初始化控件参数
	private void initWindowParams(Context context) {
		DisplayMetrics outMetrics = new DisplayMetrics();
		manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		manager.getDefaultDisplay().getMetrics(outMetrics);
		screenWidth = outMetrics.widthPixels;
		// 给控件高度设置初始值
		menuheight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48,
				getResources().getDisplayMetrics());

	}

	/**
	 * 设置三个按钮的父布局（LinearLayout）高度
	 * 
	 * @param dip
	 */
	boolean resetTab = false;

	public void setTabHeight(int dip) {
		this.menuheight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
				getResources().getDisplayMetrics());
		resetTab = true;
	}

	@Override
	public void onClick(View v) {
		TextLayout mChoosedbtn = (TextLayout) v;
		int currChoose = (Integer) mChoosedbtn.getTag();
		switch (currChoose) {
		case OPTION_ONE:
			showPopupWindow(mListViewOptionOne, OPTION_ONE);
			break;
		case OPTION_TWO:
			showPopupWindow(mListViewOptionTwo, OPTION_TWO);
			break;
		case OPTION_THIRD:
			showPopupWindow(mListViewOptionThree, OPTION_THIRD);
			break;
		default:
			Toast.makeText(getContext(), "?", Toast.LENGTH_SHORT).show();
			break;
		}

	}

	private void disMissPpw() {
		setCloseCallback();
		if (ppw != null) {
			ppw.dismiss();
			ppw = null;
		}
	}

	private void showPopupWindow(View contentView, int option) {
		int ppwHeight = getPpwHeight(option, false);
		int maxHeight = getPpwHeight(option, true) * 10;
		this.currOption = option;
		setExpendCallback(option);
		ppw = new PopupWindow(contentView, screenWidth, ppwHeight >= maxHeight ? maxHeight : LayoutParams.WRAP_CONTENT,
				true);
		// 设置dismiss监听和背景后，当点击外部时，会触发监听
		ColorDrawable dw = new ColorDrawable(Color.parseColor("#ffffff"));
		ppw.setBackgroundDrawable(dw);
		if (styleRes != 0) {
			ppw.setAnimationStyle(styleRes);
		} else {
			ppw.setAnimationStyle(R.style.mMenuTheme);
		}
		ppw.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				disMissPpw();
			}
		});
		ppw.showAsDropDown(mLvFirstBtn, 0, 0);
	}

	private void setExpendCallback(int option) {
		if (expendlistener != null) {
			expendlistener.onExpended(option);
		}
		// TODO
		TextLayout button = getButton(currOption);
		ImageView arrow = button.getArrow();
		button.setTextColor(expendRes);
		rotate(arrow, 0, 180);

	}

	private void rotate(ImageView arrow, int from, int to) {
		RotateAnimation anim = new RotateAnimation(from, to, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		anim.setDuration(300);
		anim.setFillAfter(true);
		arrow.startAnimation(anim);
	}

	public void setTabTextRes(int expendRes, int closeRes) {
		this.expendRes = expendRes;
		this.closeRes = closeRes;
	}

	private void setCloseCallback() {
		if (closelistener != null) {
			closelistener.onExpended(currOption);
		}
		TextLayout button = getButton(currOption);
		ImageView arrow = button.getArrow();
		button.setTextColor(closeRes);
		rotate(arrow, 180, 0);

	}

	/**
	 * 设置菜单每个条目的高度，用来动态计算菜单的总体高度,最多一次显示8个
	 * 
	 * @param itemHightDp
	 */
	public void setItemHeight(int itemHightDp) {
		this.itemHightDp = itemHightDp;
	}

	/*
	 * 返回条目数*条目高度，如果isDefault=true则返回单个条目高度（默认40dp）
	 */
	private int getPpwHeight(int option, boolean isDefault) {
		int itemHighPx = 0;
		if (isDefault) {
			if (itemHightDp != 0) {
				itemHighPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, itemHightDp,
						getResources().getDisplayMetrics());
			} else {
				itemHighPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40,
						getResources().getDisplayMetrics());
			}
			return itemHighPx;
		}

		if (itemHightDp != 0) {
			itemHighPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, itemHightDp,
					getResources().getDisplayMetrics());
		} else {
			itemHighPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40,
					getResources().getDisplayMetrics());
		}
		int itemCount = 0;
		switch (option) {
		case OPTION_ONE:
			itemCount = optionOne.size();
			break;
		case OPTION_TWO:
			if (isSecondRelevancy) {
				itemCount = smartSecondRelevancy.get(mLvFirstBtn.getText()).size();
			} else if (isThirdRelevancy) {
				optionTwo.size();
			} else {
				itemCount = optionTwo.size();
			}
			break;
		case OPTION_THIRD:
			itemCount = optionThree.size();
			break;
		default:
			itemCount = 5;
			break;
		}

		return itemCount * itemHighPx;
	}

	private ListView getListView(List<String> options) {
		ListView lv = new ListView(getContext());
		// 初始化参数
		android.view.ViewGroup.LayoutParams params = new LayoutParams(screenWidth, LayoutParams.WRAP_CONTENT);
		lv.setLayoutParams(params);
		lv.setDivider(null);
		// 设置布局
		ArrayAdapter<String> adapter = getAdapter(options);
		lv.setAdapter(adapter);
		return lv;
	}

	private ArrayAdapter<String> getAdapter(List<String> options) {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.smartmenu_item,
				R.id.tv_smartmenu, options);
		return adapter;
	}

	/**
	 * 获取当前三个标签的内容
	 * 
	 * @return
	 */
	public List<String> getItemCurrentState() {
		List<String> items = new ArrayList<String>();
		items.add(mLvFirstBtn.getText().toString());
		items.add(mLvSecBtn.getText().toString());
		if (mLvThirdBtn != null) {
			items.add(mLvThirdBtn.getText().toString());
		}
		return items;
	}

	public void setOnMenuClickListener(OnMenuClickListener listener) {
		this.listener = listener;
	}

	public void setOnMenuExpendListener(OnMenuExpendListener listener) {
		this.expendlistener = listener;
	}

	public void setOnMenuCloseListener(OnMenuCloseListener listener) {
		this.closelistener = listener;
	}

	public interface OnMenuClickListener {
		public void onMenuClick(String menu1, String menu2, String menu3);
	}

	public interface OnMenuExpendListener {
		public void onExpended(int option);
	}

	public interface OnMenuCloseListener {
		public void onExpended(int option);
	}
}
